import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage } from "umi-plugin-react/locale";
import { Row, Col, Card, Icon, Tooltip, Form, Input, Tree, Button, message, Modal, Spin, Select, TreeSelect } from "antd";
import styles from "./index.less";
import UserSession from "@/UserSession";
import { setFileCategory, editFileCategory, delFileCategory, setUpOrDownFileCategory, getFileCategoryTree, getDocCategoryTree } from '@/services/knowledgeFile';
const { TreeNode, DirectoryTree } = Tree;
const FormItem = Form.Item;
const TreeNodes = TreeSelect.TreeNode;
const { confirm } = Modal;
import icon1 from "@/assets/overview/1.png";
import icon2 from "@/assets/overview/2.png";
import icon4 from "@/assets/overview/4.png";
import icon6 from "@/assets/overview/6.png";
import icon7 from "@/assets/overview/7.png";
import chu from "@/assets/overview/chu.png";
import jin from "@/assets/overview/jin.png";

class LeftTree extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataTree: [],
            iconJudge: true,
            defaultExpandAll: true,
            selectedKeys: null,
            path: "", // 父节点名称
            path: "",
            disabled: null,
            disablex: null,
            showModel: false,
            cid: null,
            title: "",
            loading: false,
            moveShow: false,
            value: undefined,
            parentPathMove: "",
            targetRobotId: "",
            open: [],
            openB: [],
            dataTreeB: [],
            selectedKeysB: null,
            pathB: "",
            parentPathB: "",
            cidB: null,
            titleB: "",
            targetRobotIdB: "",
            buttonDJ: false,
            buttonNonew: false,
            qaListCz: "",
            isShared: false,
            parentId: "",
            expandedKeys: [],
            autoExpandParent: true,
            rootNode: "",
        };
    }

    componentWillReceiveProps(nextProps, nextContext) {
        if (this.props.onRef) {
            this.props.onRef(this);
        };
        if (nextProps.qaListCz !== this.state.qaListCz) {
            this.setState({ qaListCz: nextProps.qaListCz });
        }
    }

    fetch = (flag) => {
        this.setState({ loading: true });
        const { location: { query }, dispatch, currentUser, categoryId } = this.props;
        // console.log(this.props);
        this.reqRef = requestAnimationFrame(async () => {
            if (!UserSession.isAdmin() && UserSession.isSystemKnowledge()) {
                let res = await getDocCategoryTree({ rootCategoryId: categoryId });
                if (res && res[0]) {
                    if (flag === 100) {
                        this.setState({ dataTree: res, loading: false });
                    } else {
                        // 判断展开收起状态
                        const childrenIds = [res[0].id];
                        this.localStorageKeys(childrenIds);
                        // 判断节点选中状态 传入所有分类的节点信息，如果没有储存的节点，则选中所有分类节点
                        let obj = { cid: res[0].id, title: res[0].name, parentId: res[0].parentId, path: res[0].path, };
                        if (query && query.fileCategoryId) {
                            let dataObj = [];
                            function arrData(arr) {
                                arr.forEach(ele => {
                                    if (ele.children) {
                                        dataObj.push({ ...ele, children: undefined });
                                        arrData(ele.children)
                                    } else {
                                        dataObj.push(ele)
                                    }
                                });
                            };
                            arrData(res);
                            let objobj = dataObj.filter(item => item.id === query.fileCategoryId) && dataObj.filter(item => item.id === query.fileCategoryId).length > 0 ? dataObj.filter(item => item.id === query.fileCategoryId)[0] : null;
                            obj = objobj ? { cid: objobj.id, title: objobj.name, parentId: objobj.parentId, path: objobj.path, } : obj;
                            this.localStorageCurrentNode(obj);
                        } else {
                            this.localStorageCurrentNode(obj);
                        };
                        // 记录所有分类的id，用于当默认选中所有分类时，判断分类的操作按钮
                        this.setState({ dataTree: res, loading: false, rootNode: res[0].id });
                    }
                };
                this.setState({ loading: false });
            } else {
                let res = await getFileCategoryTree({ rootCategoryId: categoryId });
                if (res && res[0]) {
                    if (flag === 100) {
                        this.setState({ dataTree: res, loading: false });
                    } else {
                        // 判断展开收起状态
                        const childrenIds = [res[0].id];
                        this.localStorageKeys(childrenIds);
                        // 判断节点选中状态 传入所有分类的节点信息，如果没有储存的节点，则选中所有分类节点
                        let obj = { cid: res[0].id, title: res[0].name, parentId: res[0].parentId, path: res[0].path, };
                        if (query && query.fileCategoryId) {
                            let dataObj = [];
                            function arrData(arr) {
                                arr.forEach(ele => {
                                    if (ele.children) {
                                        dataObj.push({ ...ele, children: undefined });
                                        arrData(ele.children)
                                    } else {
                                        dataObj.push(ele)
                                    }
                                });
                            };
                            arrData(res);
                            let objobj = dataObj.filter(item => item.id === query.fileCategoryId) && dataObj.filter(item => item.id === query.fileCategoryId).length > 0 ? dataObj.filter(item => item.id === query.fileCategoryId)[0] : null;
                            obj = objobj ? { cid: objobj.id, title: objobj.name, parentId: objobj.parentId, path: objobj.path, } : obj;
                            this.localStorageCurrentNode(obj);
                        } else {
                            this.localStorageCurrentNode(obj);
                        };
                        // 记录所有分类的id，用于当默认选中所有分类时，判断分类的操作按钮
                        this.setState({ dataTree: res, loading: false, rootNode: res[0].id });
                    }
                };
                this.setState({ loading: false });
            }
        });
    };

    /**
     * 处理记忆展开收起状态
     * @param keys
     */
    localStorageKeys = (keys) => {
        // 先判断有没有储存的展开收起 如果没有则展开所有分类节点，如果有，则展开储存的节点
        const treeExpandedKeys = window.localStorage.getItem("treeExpandedFileKeys");
        if (treeExpandedKeys) {
            this.setState({ expandedKeys: treeExpandedKeys.split(",") });
        } else {
            window.localStorage.setItem("treeExpandedFileKeys", keys);
            this.setState({ expandedKeys: keys });
        }
    };

    /**
     * 处理记忆选中节点
     */
    localStorageCurrentNode = (obj) => {
        const { cid, parentId, path, title } = obj;
        this.setState({ cid, parentId, title, path, selectedKeys: cid, });
        // 控制右侧展示知识点
        this.props.getListByTreeRoot({ id: obj.cid, path: obj.path, parentId: obj.parentId, title: obj.title });
    };

    componentWillMount() {
        this.setState({ loading: true });
    }

    componentDidMount() {
        if (this.props.onRef) {
            this.props.onRef(this)
        }
    }

    openedTreeNodes(data) {
        return data.map((item) => {
            let a = this.state.open;
            if (item.children) {
                if (item.data.opened) {
                    a.push(item.id);
                };
                this.openedTreeNodes(item.children);
            };
            this.setState({ open: a });
        });
    }

    onSelect = (selectedKeys, info) => {
        const { location: { pathname }, dispatch } = this.props;
        let cid = selectedKeys[0];
        dispatch(routerRedux.push({ pathname, query: { fileCategoryId: cid } }));
        if (cid) {
            // 控制菜单一直被选中，不会再次点击取消
            this.setState({ selectedKeys: cid });
            let numbers = cid.lastIndexOf("-");
            let c = cid.slice(0, numbers);
            if (info.node._reactInternalFiber.pendingProps.info) {
                let nodeInfo = info.node._reactInternalFiber.pendingProps.info;
                if (nodeInfo.parentId === "0") {
                    this.setState({ buttonDJ: true }); // 判断选中所有分类按钮是否禁用
                } else {
                    this.setState({ buttonDJ: false }); // 判断选中所有分类按钮是否禁用
                };
                if (nodeInfo.disabled && nodeInfo.parentId != "0") {
                    this.setState({ buttonDJ: true }); // 判断选中所有分类按钮是否禁用
                } else if (!nodeInfo.disabled && nodeInfo.parentId != "0") {
                    this.setState({ buttonDJ: false });
                };
                const { disabled, path, parentId } = info.node._reactInternalFiber.pendingProps.info;
                const { title } = info.node._reactInternalFiber.pendingProps;
                this.setState({ path, disabled, cid, title, targetRobotId: c, isShared: false, parentId });
                this.props.terrNodeId(cid, title, info.node.props.info.path, false, parentId);
            }
        };

        // 如果该节点下又子菜单，则触发点击菜单展开收起的方法
        const nodeChildren = info.node.getNodeChildren();
        if (nodeChildren.length > 0) {
            this.onClickToCollapse(info.node.props.eventKey);
        };

        // 选中后存入local Storage
        // console.log(info.node.props);
        const obj = {
            cid: info.node.props.eventKey,
            parentId: info.node.props.info.parentId,
            title: info.node.props.title,
            path: info.node.props.info.path,
        };
        window.localStorage.setItem("currentNode", JSON.stringify(obj));
    };

    /**
     * 触发点击菜单展开收起的方法
     * @param cid
     */
    onClickToCollapse = (cid) => {
        let { expandedKeys } = this.state;
        let expandedKeysNew = [];
        if (expandedKeys.indexOf(cid) === -1) {
            expandedKeys.push(cid);
            expandedKeysNew = expandedKeys;
        } else {
            const index = expandedKeys.indexOf(cid);
            expandedKeysNew = expandedKeys.filter((item, i) => i != index);
        };
        this.doExpand(expandedKeysNew);
    };

    renderTreeNodes(data) {
        const { expandedKeys, selectedKeys } = this.state;
        return data.map((item) => {
            if (item.children) {
                return (
                    <TreeNode
                        className={item.disabled ? "glo" : ""}
                        title={item.name}
                        key={item.id}
                        info={{ path: item.path, parentId: item.parentId, disabled: item.disabled, weight: item.weight, }}
                        icon={expandedKeys.indexOf(item.id) === -1 ? (
                            <img src={staticPath + "/sysKnowledge/unfold.png"} />
                        ) : (
                            <img src={staticPath + "/sysKnowledge/fold.png"} />
                        )}
                    >
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            };
            return (
                <TreeNode
                    isLeaf={true}
                    title={item.name}
                    key={item.id}
                    info={{ path: item.path, parentId: item.parentId, disabled: item.disabled, weight: item.weight, }}
                    icon={<img src={staticPath + "/sysKnowledge/leaf.png"} />}
                    switcherIcon={<Icon type="minus-square" />}
                />
            );
        });
    }

    move(data) {
        return data.map((item) => {
            if (item.children) {
                if (item.data.disabled) {
                    return (
                        <TreeNodes className='glo' value={item.text} title={item.text} key={item.id} tcx={item.data}>{this.move(item.children)}</TreeNodes>
                    );
                } else {
                    return (
                        <TreeNodes value={item.text} title={item.text} key={item.id} tcx={item.data}>{this.move(item.children)}</TreeNodes>
                    );
                }
            };
            return (
                <TreeNodes value={item.text} title={item.text} key={item.id} tcx={item.data} />
            );
        });
    }

    unfoldIcon = () => {
        // 显示
        if (this.state.isShared) {
            return message.info("共享知识点不支持该操作");
        };
        this.setState({ iconJudge: false });
    };

    hiddenIcon = () => {
        // 隐藏
        this.setState({ iconJudge: true });
    };

    deleteCategory = () => {
        // 删除
        const { cid, selectedKeys } = this.state;
        const that = this;
        if (!selectedKeys || selectedKeys.length === 0) {
            return message.error("您还未选择需要删除的节点");
        };
        confirm({
            title: "是否删除该节点?",
            okText: "确定",
            okType: "danger",
            cancelText: "取消",
            onOk() {
                that.deleteOk();
            },
            onCancel() { },
        });
    };

    deleteOk = () => {
        const { dispatch } = this.props;
        const { path, cid } = this.state;
        this.reqRef = requestAnimationFrame(async () => {
            let res = await delFileCategory({ id: cid });
            // console.log(res);
            if (res.code == 0) {
                message["info"](`${res.message}`);
                // 删除节点后要同步删除存储的节点
                window.localStorage.removeItem("currentNode");
                this.fetch(true);
            }
        });
    };

    upOrDownCategory = (number) => {
        const { cid, dataTree, selectedKeys } = this.state;
        if (!selectedKeys || selectedKeys.length === 0) {
            return message.error("您还未选择需要操作的节点");
        };
        this.queryParentNode(dataTree, cid, number);
    };

    /**
     * 获取当前节点的数据（用于上移下移）
     * @returns {MessageType}
     */
    queryParentNode = (data, currentNodeId, type) => {
        for (const item of data) {
            if (currentNodeId === item.id) {
                this.queryBrotherNode(data, item, type);
            };
            if (item.children) {
                this.queryParentNode(item.children, currentNodeId, type);
            }
        }
    };

    /**
     * 获取当前节点的兄弟节点
     * @returns {MessageType}
     */
    queryBrotherNode = (data, item, type) => {
        let brotherId = null;
        data.map((dataItem, index) => {
            if (dataItem.id === item.id) {
                if (type === 0 && index === 0) {
                    message.error("当前节点已是第一位，无法上移");
                    return false;
                };
                if (type === 1 && index === data.length - 1) {
                    message.error("当前节点已是最后一位，无法下移");
                    return false;
                };
                if (type === 0) {
                    // 上移
                    brotherId = data[index - 1].id;
                };
                if (type === 1) {
                    // 下移
                    brotherId = data[index + 1].id;
                }
            }
        });
        if (brotherId) {
            this.doUpOrDown(brotherId);
        }
    };

    /**
     * 上移下移请求接口
     * @returns {MessageType}
     */
    doUpOrDown = (brotherId) => {
        const { dispatch } = this.props;
        const { cid } = this.state;
        this.reqRef = requestAnimationFrame(async () => {
            let res = await setUpOrDownFileCategory({ id: cid, targetId: brotherId });
            // console.log(res);
            if (res.code == 0) {
                message["info"](`${res.message}`);
                this.fetch(100);
            }
        });
    };

    businessWay = () => {
        // 修改节点名
        let userInfo = this.props.form.getFieldsValue();
        this.props.form.validateFields((err, values) => {
            if (err) {
                return false;
            };
            const { dispatch } = this.props;
            const { path, cid } = this.state;
            this.reqRef = requestAnimationFrame(async () => {
                let res = await editFileCategory({ categoryName: userInfo.businessName, id: cid });
                // console.log(res);
                if (res.code == 0) {
                    this.props.form.setFields({ businessName: "" });
                    this.props.form.setFields({ addName: "" });
                    message["info"](`${res.message}`);
                    // 修改节点后，要同步修改存储的节点信息
                    let currentNode = JSON.parse(window.localStorage.getItem("currentNode"));
                    currentNode.title = userInfo.businessName;
                    window.localStorage.setItem("currentNode", JSON.stringify(currentNode));
                    this.setState({ showModel: false, title: userInfo.businessName });
                    this.fetch();
                }
            });
        });
    };

    revisionName = () => {
        const { selectedKeys, title } = this.state;
        if (selectedKeys) {
            this.setState({ showModel: true }, () => {
                this.props.form.setFieldsValue({ businessName: title });
            });
        } else {
            message["error"]("您还未选择需要修改名称的节点");
        }
    };

    addName = () => {
        // 添加分类名 addClassify
        const { categoryId } = this.props;
        let userInfo = this.props.form.getFieldsValue();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let str = userInfo.addName;
                let val = str.replace(/\s*/g, "");
                let Regx = /^[A-Za-z0-9\u4e00-\u9fa5]*$/;
                if (Regx.test(val)) {
                    if (val.length < 21 && val.length > 0) {
                        let a = str.replace(/\s*/g, "");
                        const { dispatch } = this.props;
                        const { path, cid, parentId } = this.state;
                        this.reqRef = requestAnimationFrame(async () => {
                            let res = await setFileCategory({ categoryName: a, parentId: cid, rootCategoryId: categoryId });
                            // console.log(res);
                            if (res.code == 0) {
                                this.props.form.setFields({ addName: "" });
                                message["info"](`${res.message}`);
                                this.setState({ showModelA: false });
                                this.fetch();
                                const treeExpandedKeys = window.localStorage.getItem("treeExpandedFileKeys");
                                if (treeExpandedKeys) {
                                    let expandedKeys = treeExpandedKeys.split(",");
                                    if (expandedKeys.indexOf(cid) === -1) {
                                        expandedKeys.push(cid);
                                    };
                                    window.localStorage.setItem("treeExpandedFileKeys", expandedKeys);
                                    this.setState({ expandedKeys });
                                }
                            }
                        });
                    } else if (val.length === 0) { } else {
                        message.error("分类名称不能为空，不能含有特殊字符，且长度不大于20！操作失败");
                    }
                } else {
                    message.error("分类名称不能为空，不能含有特殊字符，且长度不大于20！操作失败");
                }
            }
        });
    };

    addsName = () => {
        const { selectedKeys } = this.state;
        if (selectedKeys) {
            this.setState({ showModelA: true });
        } else {
            message["error"]("您还未选择需要添加分类的节点");
        }
    };

    checkFieldForCategoryName(rule, value, callback) {
        const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/g;
        if (rule.field === "businessName" || rule.field === "addName") {
            if (value) {
                if (reg.test(value)) {
                    if (value.length > 20 || value.length < 0) {
                        callback("支持20位以内大小写字母、数字和中文");
                    } else {
                        callback();
                    }
                } else {
                    callback("支持20位以内大小写字母、数字和中文");
                }
            } else {
                callback("支持20位以内大小写字母、数字和中文");
            }
        }
    }

    /**
     * 分类树展开收起的回调
     */
    doExpand = (expandedKeys, node) => {
        window.localStorage.setItem("treeExpandedFileKeys", expandedKeys);
        this.setState({ expandedKeys, autoExpandParent: false });
    };

    render() {
        const { iconJudge, expandedKeys, autoExpandParent, selectedKeys, rootNode } = this.state;
        const { getFieldDecorator } = this.props.form;
        const FormItemLayont = {
            labelCol: {
                xs: 24,
                sm: 5,
            },
            wrapperCol: {
                xs: 24,
                sm: 19,
            },
        };
        const buttonDJ = this.state.buttonDJ || (!UserSession.isAdmin() && UserSession.isSystemKnowledge()) ? { pointerEvents: "none", opacity: "0.5" } : null;
        const buttonNonew = this.state.buttonNonew || (!UserSession.isAdmin() && UserSession.isSystemKnowledge()) ? { pointerEvents: "none", opacity: "0.5" } : null;
        const { authority, location: { query } } = this.props;

        return (
            <div style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                <div className={styles.topBar}>
                    {iconJudge === true ? (
                        <div>
                            <span style={{ paddingTop: 2, fontWeight: 600 }}>我的空间</span>
                            {!this.state.isShared && authority === 2 ? (
                                <div onClick={this.unfoldIcon} style={{ float: "right", cursor: "pointer", paddingBottom: 9, fontSize: 16 }}>
                                    <img style={{ paddingBottom: 5 }} src={jin} />
                                </div>
                            ) : null}
                        </div>
                    ) : (
                        <div className={styles.bj}>
                            <Tooltip placement='top' title='上移' arrowPointAtCenter>
                                <img
                                    src={icon1}
                                    style={rootNode === selectedKeys ? { pointerEvents: "none", opacity: "0.5" } : buttonDJ}
                                    onClick={() => this.upOrDownCategory(0)}
                                    className={styles.iconsNew}
                                />
                            </Tooltip>
                            <Tooltip placement='top' title='下移' arrowPointAtCenter>
                                <img
                                    src={icon2}
                                    style={rootNode === selectedKeys ? { pointerEvents: "none", opacity: "0.5" } : buttonDJ}
                                    onClick={() => this.upOrDownCategory(1)}
                                    className={styles.iconsNew}
                                />
                            </Tooltip>
                            <Tooltip placement='top' title='删除分类' arrowPointAtCenter>
                                <img
                                    src={icon4}
                                    style={rootNode === selectedKeys || (!UserSession.isAdmin() && UserSession.isSystemKnowledge()) ? { pointerEvents: "none", opacity: "0.5" } : buttonDJ}
                                    className={styles.iconsNew}
                                    onClick={this.deleteCategory}
                                />
                            </Tooltip>
                            <Tooltip placement='top' title='修改名称' arrowPointAtCenter>
                                <img
                                    style={rootNode === selectedKeys || (!UserSession.isAdmin() && UserSession.isSystemKnowledge()) ? { pointerEvents: "none", opacity: "0.5" } : buttonDJ}
                                    onClick={this.revisionName}
                                    className={styles.iconsNew}
                                    src={icon6}
                                />
                            </Tooltip>
                            <Tooltip placement='top' title='添加分类' arrowPointAtCenter>
                                <img style={buttonNonew} onClick={this.addsName} className={styles.iconsNew} src={icon7} />
                            </Tooltip>
                            <Tooltip placement='top' title='返回' arrowPointAtCenter>
                                <img onClick={this.hiddenIcon} className={styles.iconsNew} src={chu} style={{ height: 14, marginTop: 3 }} />
                            </Tooltip>
                        </div>
                    )}
                </div>
                <Spin className={styles.spin} spinning={this.state.loading}>
                    {this.state.dataTree.length === 0 ? null : (
                        <DirectoryTree
                            onSelect={this.onSelect}
                            expandedKeys={expandedKeys}
                            onExpand={this.doExpand}
                            showIcon={true}
                            autoExpandParent={autoExpandParent}
                            selectedKeys={[query?.fileCategoryId ? query.fileCategoryId : selectedKeys]}
                            showLine={true}
                        >
                            {this.renderTreeNodes(this.state.dataTree)}
                        </DirectoryTree>
                    )}
                </Spin>
                <Modal
                    className='modelZdy'
                    title='修改节点名称'
                    visible={this.state.showModel}
                    okText={<FormattedMessage id='app.customDictionary.save' />}
                    cancelText={<FormattedMessage id='app.customDictionary.cancel' />}
                    onCancel={() => {
                        this.props.form.setFields({ businessName: "" });
                        this.setState({ showModel: false });
                    }}
                    onOk={this.businessWay}
                    destroyOnClose
                >
                    <Form layout='horizontal'>
                        <FormItem label='新节点名' {...FormItemLayont}>
                            {getFieldDecorator("businessName", {
                                rules: [
                                    { required: this.state.showModel, message: "节点名不能为空" },
                                    { validator: this.state.showModel ? this.checkFieldForCategoryName : "", },
                                ],
                            })(<Input onPressEnter={this.businessWay} />)}
                        </FormItem>
                    </Form>
                </Modal>
                <Modal
                    className='modelZdy'
                    title='添加分类'
                    visible={this.state.showModelA}
                    okText={<FormattedMessage id='app.customDictionary.save' />}
                    cancelText={<FormattedMessage id='app.customDictionary.cancel' />}
                    onCancel={() => {
                        this.props.form.setFields({ addName: "" });
                        this.setState({ showModelA: false });
                    }}
                    onOk={this.addName}
                    destroyOnClose
                >
                    <Form layout='horizontal'>
                        <FormItem label='添加分类名' {...FormItemLayont}>
                            {getFieldDecorator("addName", {
                                initialValue: "",
                                rules: [
                                    { required: this.state.showModelA, message: "分类名不能为空", },
                                    { validator: this.state.showModelA ? this.checkFieldForCategoryName : "", },
                                ],
                            })(<Input onPressEnter={this.addName} />)}
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default connect(({ user }) => ({
    currentUser: user.currentUser,
}))(Form.create()(LeftTree));
